package com.adv.crm.services.impl;

import com.adv.crm.beans.CustomerBean;
import com.adv.crm.beans.PageBean;
import com.adv.crm.beans.WarpPageResponse;
import com.adv.crm.beans.WarpResponse;
import com.adv.crm.dao.CustomerDao;
import com.adv.crm.services.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by 16978 on 2016/7/30.
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao;

    @Override
    public WarpPageResponse<List<CustomerBean>> getCustomers(int pageIndex, int pageSize) {
        WarpPageResponse<List<CustomerBean>> response = new WarpPageResponse<List<CustomerBean>>();
        Integer offset = (pageIndex - 1) * pageSize;
        List<CustomerBean> customers = customerDao.getCustomersByPage(offset, pageSize);
        response.setData(customers);
        int count = customerDao.getCustomerCount();
        PageBean page = new PageBean();
        getPageCount(pageSize, page, count);
        response.setPage(page);
        return response;
    }

    @Override
    public WarpResponse<List<CustomerBean>> getAllCustomer() {
        WarpResponse<List<CustomerBean>> response = new WarpResponse<List<CustomerBean>>();
        List<CustomerBean> customers = customerDao.getAllCustomer();
        response.setData(customers);
        return response;
    }

    @Override
    public CustomerBean getCustomerById(int id) {
        return customerDao.getCustomerById(id);
    }

    @Override
    public WarpResponse<String> insertCustomer(CustomerBean bean) {
        WarpResponse<String> response = new WarpResponse<String>();
        int result = customerDao.insertCustomer(bean);
        response.setMsg("");
        return response;
    }

    @Override
    public WarpResponse<String> updateCustomer(CustomerBean bean) {
        WarpResponse<String> response = new WarpResponse<String>();
        int result = customerDao.updateCustomer(bean);
        response.setMsg("");
        return response;
    }

    @Override
    public WarpResponse<String> deleteCustomerById(int id) {
        WarpResponse<String> response = new WarpResponse<String>();
        int result = customerDao.deleteCustomerById(id);
        if (result > 0) {
            response.setSuccess(true);
        } else {
            response.setSuccess(false);
        }
        return response;
    }


    private PageBean getPageCount(int pageSize, PageBean pageBean, Integer total) {
        int count = 1;
        if (total != null) {
            count = total / pageSize;
            if (total % pageSize > 0) {
                count += 1;
            }
            pageBean.setPageCount(count);
        }
        return pageBean;
    }
}
